package com.janyee.powerdroid

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity


abstract class BaseActivity : AppCompatActivity() {


    internal abstract val permissions: Array<String>

    private var mPermissionsChecker: PermissionsChecker? = null // 权限检测器

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPermissionsChecker = PermissionsChecker(this)
    }

    override fun onResume() {
        super.onResume()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && mPermissionsChecker!!.lacksPermissions(*permissions)) {
            startPermissionsActivity()
        }
    }

    private fun startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, PERMISSION_REQUEST_CODE, *permissions)
    }

    protected fun onPermissionDenied() {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == PERMISSION_REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            onPermissionDenied()
        }
    }

    companion object {
        private val PERMISSION_REQUEST_CODE = 0 // 请求码
    }

}
